<html>
<head>
<title>CS 143 Calculator: Kyle Morton</title>
</head>

Enter an expression to be evaluated.

Only addition/subtraction and multiplication/division allowed. Parentheses not supported.

<p>
<form method="post">
<input type="text" name="input"><input type="submit" value="evaluate">
</form>
</p>

<body>
<?php
function calculate($input)
{
	$newstr = preg_replace("/[0-9\.]+\/-?0[0-9]*/", "0", $input);
	while($newstr != $input)
	{
		$input = $newstr;
		$newstr = preg_replace("/[0-9.]+\/0[0-9]*/", "0", $input);
	}

	$errorstr = "Invalid expression: " . $input;
	
	if(preg_match("/[^0-9\.+\-\/\*]/", $input))
	{
		return $errorstr;
	}
	
	if(preg_match("/[\/*+\-][\/*+]/", $input))
	{
		return $errorstr;
	}

	if(preg_match("/--/", $input))
	{
		return $errorstr;
	}

	if(preg_match("/^[\/+*]/", $input))
	{
		return $errorstr;
	}

	if(preg_match("/[\/+\-*]$/", $input))
	{
		return $errorstr;
	}

	if(preg_match("/^\.$/", $input))
	{
		return $errorstr;
	}

	if(preg_match("/^\.[^0-9]+/", $input))
	{
		return $errorstr;
	}

	if(preg_match("/[^0-9]+\.$/", $input))
	{
		return $errorstr;
	}

	if(preg_match("/[0-9]*\.[0-9]*\./", $input))
	{
		return $errorstr;
	}

	eval("\$str = " . $input . ";");
	return "The result is: " . $str;
}
 
echo calculate($_POST["input"]);
?>
</body>

</html>
